import axios from 'axios'
import Storeage from "./StorageUtil"
import Elmentui from "element-ui"
import store from "@/store"
import router from "@/router"
import Cookie from 'js-cookie'

export function time(tamp) {
  return timestampToTime(tamp)
}

Date.prototype.Format = function (fmt) {
  let o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds()
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
  return fmt
}

//跨域凭证
axios.defaults.withCredentials = true

axios.interceptors.request.use(res => {
  let token = Cookie.get("token")
  let header = store.state.header;
  if (token != undefined && token.trim() != "" && header.trim() != "") res.headers[header] = token
  return res
})

axios.interceptors.response.use(response => {
  let res = response.data
  if (res.code == 200) return res
  else if (res.code == 401 || res.code == 403) {
    store.commit("clear")
    store.commit("reset")
    Cookie.remove('token')
    router.replace("/login")
  } else if (res.code == 404) {
    Elmentui.Message.warning("当前访问的内容不存在")
    router.replace("/404")
  } else if (res.code == 400) {
    //防止下载文件的时候出现莫名的弹窗
  } else {
    // Elmentui.Message.warning(res.msg)
  }
  return res
}, error => {
  return error.data
})

function timestampToTime(timestamp) {
  let date = new Date(timestamp),
    Y = date.getFullYear() + '-',
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
    D = date.getDate() + ' ',
    h = date.getHours() + ':',
    m = date.getMinutes() + ':',
    s = date.getSeconds()
  return Y + M + D + h + m + s
}

export default {

  post(url, data, config = {}) {
    return axios({
      method: 'post',
      url,
      data,
      timeout: config.timeout || 15000,
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      },
      ...config
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  upload(url, data) {
    let form = new FormData()
    Object.keys(data).forEach(value => {
      form.append(value, data[value])
    })
    return axios({
      method: 'post',
      url,
      data,
      transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }],
      timeout: 15000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  get(url, params) {
    return axios({
      method: 'get',
      url,
      params,
      timeout: 15000
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    ).catch(e => {

    })
  },
  put(url, data) {
    return axios({
      method: 'put',
      baseURL: process.env.BASE_API,
      url,
      data,
      timeout: 15000
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  down(url, data, fileType = '', fileName = '') {
    return axios({
      method: 'get',
      url,
      data,
      timeout: 300000,
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      },
      responseType: 'blob'
    }).then(res => {
      // let split=res.headers['content-disposition'].split('=')
      let fileReader = new FileReader()
      fileReader.readAsDataURL(res)
      fileReader.onload = e => {
        let a = document.createElement('a')
        a.download = fileType ? 'file' + fileType : 'file' + data.fileType
        a.href = e.target.result
        document.children[0].appendChild(a)
        a.click()
        document.children[0].removeChild(a)
      }
      return res
    })
  },
  downs(url, data, fileType = '', fileName = '') {
    return axios({
      method: 'post',
      url,
      data,
      timeout: 300000,
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      },
      responseType: 'blob'
    }).then(res => {
      // let split=res.headers['content-disposition'].split('=')
      let fileReader = new FileReader()
      fileReader.readAsDataURL(res)
      fileReader.onload = e => {
        let a = document.createElement('a')
        a.download = fileType ? 'file' + fileType : 'file' + data.fileType
        a.href = e.target.result
        document.children[0].appendChild(a)
        a.click()
        document.children[0].removeChild(a)
      }
      return res
    })
  },
  delete(url, params) {
    return axios({
      method: 'delete',
      baseURL: process.env.BASE_API,
      url,
      params,
      timeout: 15000,
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  }

}
